import { nextTick, reactive, ref } from 'vue'
import { defineStore } from 'pinia'
import { useRoute } from 'vue-router'
import router from '@/router'
import { ElMessage } from 'element-plus'

const useTagStore = defineStore(
  'tagList',
  {
    state: () => ({
      route: useRoute(),
      alive: true,
      openNewPage: ['/document/fileEdit', '/document/l/files'],// 需要新开的页面列表，不能模糊匹配
      tagListCopy: [],
      tagList: [{
        name: '/home',
        fullPath: '/home',
        breadcrumbName: '首页'
      }],
    }),
    actions: {
      init() {
        // const this.route = useRoute()
        console.log(this.route, ' routerouteroute');
        if (this.route.path != '/home') {
          let breadcrumbName = this.route.meta.breadcrumbName
          if(this.route.query.name){
            breadcrumbName = this.route.query.name;
          }
          this.tagList.push({
            name: this.route.path,
            fullPath: this.route.fullPath,
            breadcrumbName: breadcrumbName,
            historyList: [
              {
                name: this.route.path,
                fullPath: this.route.fullPath,
                breadcrumbName: breadcrumbName
              }
            ]
          })
        }
      },
      addTagList(obj) {
        console.log(this.tagList, obj, 1);;
        const object = this.tagList.find(item => item.name.includes(obj.name) && item.breadcrumbName === obj.breadcrumbName||decodeURIComponent(obj.fullPath).replace(/\+/g, ' ') == decodeURIComponent(item.fullPath).replace(/\+/g, ' '));
        // let object
        // if (openNewPage.includes(obj.name)) {
        //   Object = this.tagList.find(item => item.name == obj.name)
        // } else {
        //   Object = this.tagList.find(item => item.name.includes(obj.name) && item.breadcrumbName === obj.breadcrumbName)
        // }
        console.log(object, 2);
        // 如果不存在，则添加新项
        if (!object) {
          console.log(obj, 3);
          this.tagList.push(obj);
        }
      },
      getTag(obj) {
        console.log(obj, 'getTag', this.tagList, this.route.path);
        if (obj.name && obj.breadcrumbName && obj.fullPath) {
          return this.tagList.find(item => item.name === obj.name && item.breadcrumbName === obj.breadcrumbName && item.fullPath === obj.fullPath)
        } else if (obj.breadcrumbName) {
          return this.tagList.find(item => item.breadcrumbName === obj.breadcrumbName)
        } else if (obj.fullPath) {
          return this.tagList.find(item => item.fullPath === obj.fullPath)
        } else if (obj.name) {
          return this.tagList.find(item => item.name === obj.name)
        } else {
          return this.tagList.find(item => decodeURIComponent(item.name) === decodeURIComponent(this.route.path))
        }
      },
      getFullPathTag(fullPath) {
        console.log(JSON.parse(JSON.stringify(this.tagList)),'getFullPathTag', fullPath);
        return this.tagList.find(e => decodeURIComponent(e.fullPath) === decodeURIComponent(fullPath))
      },
      refreshTagList(oldObj, newObj, type = false) {
        const object = this.getTag(oldObj);
        console.log(object, oldObj, newObj, 'refreshTagList',this.tagList, this.route);
        if(!object) return;
        object.name = newObj.name
        object.fullPath = newObj.fullPath
        object.breadcrumbName = newObj.breadcrumbName
        object.params = newObj.params
        // 添加历史记录
        if(type) {
          object.historyList = [newObj]
        } else {
          object.historyList.push(newObj)
        }
        // 去重
        nextTick(() => {
          this.tagList.forEach((item, index, self) => {
            let itemFullPath = decodeURIComponent(item.fullPath).replace(/\+/g, ' ');// 替换 + 为 空格  浏览器url转换原因
            if (index !== self.findIndex((t) => t.name === item.name && t.breadcrumbName === item.breadcrumbName || decodeURIComponent(t.fullPath).replace(/\+/g, ' ') === itemFullPath)) {
              this.tagList.splice(index, 1);
            }
          })
          console.log(this.tagList);
        });
      },
      // 回退
      historyBack(obj) {
        const object = this.getTag(obj);
        console.log(obj, 'historyBack',object);
        // if(!object.historyList||!object.historyList.length) return ElMessage.info('已经是第一页了!');
        const index = object?.historyList.findIndex(item => item.name === object.name)
        console.log(index);
        if (index === 0 || !index) {
          ElMessage({
            message: '已经是第一页了!',
            type: 'info'
          })
          return
        }
        const pre = object.historyList[index - 1]
        console.log(pre);
        object.name = pre.name
        object.fullPath = pre.fullPath
        object.breadcrumbName = pre.breadcrumbName
        console.log(object, '2030218310', object.fullPath);

        let { query } = parseFullPath(object.fullPath)
        router.push({ path: object.name, query: query })
      },
      // 前进
      historyFoward(obj) {
        const object = this.getTag(obj);
        const index = object.historyList.findIndex(item => item.name === object.name)
        console.log(object, index);
        if (index == object.historyList.length - 1) {
          ElMessage({
            message: '已经是最后一个页面!',
            type: 'info'
          })
          return
        }
        const next = object.historyList[index + 1]
        object.name = next.name
        object.fullPath = next.fullPath
        object.breadcrumbName = next.breadcrumbName
        console.log(object, '2030218310', object.fullPath, '21', JSON.parse(JSON.stringify(object)));
        let { query } = parseFullPath(object.fullPath)
        router.push({ path: object.name, query: query })
      },
      deleteTagList(index) {
        this.tagList.splice(index, 1)
        this.tagListCopy.splice(index, 1)
      },
      closeTagOther(list) {
        this.tagList.length = 1
        if (list.name !== '/home') {
          this.tagList.push(list)
        }
      },
      closeAllTag() {
        this.tagList.length = 1
      },
      reload() {
        alive.value = false
        nextTick(() => {
          alive.value = true
        })
      }
    }
  })
export default useTagStore;


function parseFullPath(fullPath) {
  const [path, queryString] = fullPath.split('?'); // 按 `?` 分割路径和参数
  const query = {};

  if (queryString) {
    queryString.split('&').forEach(param => {
      const [key, value] = param.split('=');
      query[key] = decodeURIComponent(value || ''); // 处理未赋值的情况
    });
  }

  return { path, query };
}